//
//  CLCycleCollectionView.m
//  Charles
//
//  Created by Leo on 2017/7/14.
//  Copyright © 2017年 charles. All rights reserved.
//

#import "CLCycleCollectionView.h"

@interface CLCycleCollectionView ()<UICollectionViewDelegate,UICollectionViewDataSource> {
    NSArray *_dataArray;
    NSMutableArray *_indexArray;
    NSInteger _groupCount;
    NSInteger currentIndex;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewLayout *flowLayout;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) Class cls;
@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, strong) UIPageControl *pageControl;

@end

@implementation CLCycleCollectionView

- (void)dealloc {
    [self removeTimer];
}

- (instancetype)initWithFrame:(CGRect)frame flowlayOut:(UICollectionViewLayout *)flowlayOut class:(Class)cls identifier:(NSString *)identifier {
    if (self = [super initWithFrame:frame]) {
        self.cls = cls;
        self.identifier = identifier;
        self.flowLayout = flowlayOut;
        [self setUpView];
    }
    return self;
}

- (void)setUpView {
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = NO;
    [_collectionView registerClass:self.cls forCellWithReuseIdentifier:self.identifier];
}

- (void)setDataArray:(NSArray *)dataArray {
    _dataArray = [NSArray arrayWithArray:dataArray];
    _indexArray = [[NSMutableArray alloc]initWithCapacity:0];
    _groupCount = 100;
    for (NSInteger i = 0; i<_groupCount; i++) {
        for (NSInteger j = 0; j< _dataArray.count; j++) {
            [_indexArray addObject:@(j)];
        }
    }
    //定位到中间
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_groupCount /2 * _dataArray.count inSection:0];
    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    if (self.isAutoScroll) {
        [self addTimer];
    }
    if (self.isShowPageControl) {
        self.pageControl.frame = CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 20);
        self.pageControl.numberOfPages = _dataArray.count;
        [self.pageControl updateCurrentPageDisplay];
    }
}
- (void)setPageEnable:(BOOL)enable {
    self.collectionView.pagingEnabled = enable;
}

- (NSArray *)indexArray {
    return _indexArray;
}

-(void)addTimer {
    [self.timer invalidate];
    self.timer = nil;
    NSTimeInterval interval = 5;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}

- (void)removeTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)nextImage {
    CGFloat W = _collectionView.frame.size.width;

    UICollectionViewFlowLayout *layOut = (UICollectionViewFlowLayout *)_collectionView.collectionViewLayout;
    CGFloat itemWith = layOut.itemSize.width;
    
    if ((int)self.collectionView.contentOffset.x % (int)W == 0) {
        CGFloat offsetX = self.collectionView.contentOffset.x + W;
        [self.collectionView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
        NSLog(@"+++++++++++++++++%lf",offsetX);
    }else {
        CGFloat offsetX = self.collectionView.contentOffset.x + W;
        [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x + itemWith + layOut.minimumLineSpacing, self.collectionView.contentOffset.y) animated:YES];
//        NSLog(@"----------------- %f",offsetX);
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _indexArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.dataSource respondsToSelector:@selector(clCycleCollectionView:cellForItemAtIndexPath:)]) {
       return [self.dataSource clCycleCollectionView:collectionView cellForItemAtIndexPath:indexPath];
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.cellSelectBlock) {
        self.cellSelectBlock(indexPath);
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.isAutoScroll) {
        [self addTimer];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollToMiddle];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (self.isAutoScroll) {
        [self scrollToMiddle];
    }
}

- (void)scrollToMiddle {
    CGPoint point = [self convertPoint:_collectionView.center toView:_collectionView];
    NSIndexPath *indexPathNow = [_collectionView indexPathForItemAtPoint:point];
    NSInteger index = indexPathNow.row % _dataArray.count;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_groupCount /2 * _dataArray.count + index inSection:0];
    [_collectionView reloadData];
    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    self.pageControl.currentPage = index;
}

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.pageIndicatorTintColor = [UIColor grayColor];
        [self addSubview:_pageControl];
    }
    return _pageControl;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        if (self.flowLayout) {
            _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.flowLayout];
            _collectionView.showsHorizontalScrollIndicator = NO;
            [self addSubview:_collectionView];
        }
        
    }
    return _collectionView;
}

@end

